<?php

class syslogistics_api_dlvpoint_addNew {

    public $apiDescription = "添加送货点";

    public function getParams()
    {
        $return['params'] = array(
            'depot_name' =>['type'=>'string','valid'=>'required|max:20', 'description'=>'仓库名称','default'=>'','example'=>'益阳'],
            'depot_bn' =>['type'=>'string','valid'=>'required|max:20', 'description'=>'仓库编码','default'=>'','example'=>'234567'],
            'name' =>['type'=>'string','valid'=>'required|max:20', 'description'=>'送货点名称','default'=>'','example'=>'商派送货点'],
            'area_id' =>['type'=>'string','valid'=>'required', 'description'=>'送货地区ID','default'=>'','example'=>'430000,430000,430102'],
            'addr' =>['type'=>'string','valid'=>'required:max:50', 'description'=>'送货详细地址','default'=>'','example'=>'桂林路396号2号楼'],
            'tel' =>['type'=>'string','valid'=>'required', 'description'=>'送货点联系方式','default'=>'','example'=>'13918765432'],
        );

        return $return;
    }

    public function create($params)
    {
        $objMdldlvpoint = app::get('syslogistics')->model('delivery_point');

        if( !area::checkArea($params['area_id']) )
        {
            throw new LogicException('请选择完整地区');
        }

        $name = $objMdldlvpoint->getRow('id', ['name'=>trim($params['name'])] );
        if( $name ) throw new LogicException('送货点名称已存在');

        $areaIds = explode(',', $params['area_id']);
        if( count($areaIds) == 2 )
        {
            $insertData['area_state_id'] = 1;
            $insertData['area_city_id'] = $areaIds[0];
            $insertData['area_district_id'] = $areaIds[1];
        }
        else
        {
            $insertData['area_state_id'] = $areaIds[0];
            $insertData['area_city_id'] = $areaIds[1];
            $insertData['area_district_id'] = $areaIds[2];
        }
        //根据送货点地址调用百度地图接口获取经纬度
        $address = area::getSelectArea($params['area_id'],'').$params['addr'];
        $ak = "CAd14de4d13fa18ebecbd5ab92af71bc";
        $url = "http://api.map.baidu.com/cloudgc/v1?ret_coordtype=bd09ll&address=$address&ak=$ak";
        $address_data = file_get_contents($url);
        $json_data = json_decode($address_data,true);
        $lat = $json_data['result']['0']['location']['lat'];
        $lng = $json_data['result']['0']['location']['lng'];
        
        $insertData['latitude'] = $lat;
        $insertData['longitude'] = $lng;
        $insertData['depot_name'] = $params['depot_name'];
        $insertData['depot_bn'] = $params['depot_bn'];
        $insertData['name'] = trim($params['name']);
        $insertData['area'] = $params['area_id'];
        $insertData['addr'] = $params['addr'];
        $insertData['tel'] = $params['tel'];

        return $objMdldlvpoint->insert($insertData);
    }
}

